package dataImport.action;

import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import dataImport.action.abstracts.AbstractTempEntityReader;
import dataImport.action.manager.EntityReaderManager;
import dataImport.action.manager.storage.EntityReaderStorageKey;
import dataImport.exception.MissingAttributeException;
import dataImport.exception.MissingReader;
import dataImport.model.Command;
import dataImport.model.CustomAction;
import dataImport.model.CustomActionTemp;
import dataImport.model.abstracts.AbstractEntity;


public class CustomActionReader extends AbstractTempEntityReader {

	private static final long serialVersionUID = 1212405523847320486L;

	public static final String ENTITY_NAME = "action";

	private static final String ATTRIBUTE_COMMAND_ID = "command";

	@Override
	protected void checkRequiredReaders(final EntityReaderManager entityReaderManager) throws MissingReader {
		entityReaderManager.contains(EntityReaderStorageKey.COMMAND);
	}

	@Override
	protected AbstractEntity createEntity(final Element element) {
		final String id = element.getAttribute(ATTRIBUTE_ID);
		final String commandId = element.getAttribute(ATTRIBUTE_COMMAND_ID);

		this.verifyRestrictions(id, commandId);

		return new CustomActionTemp(id, commandId);
	}

	@Override
	protected void fixEntities(final HashMap<String, AbstractEntity> newEntities, final EntityReaderManager entityReaderManager) throws MissingReader {
		final CommandReader commandReader = entityReaderManager.getCommandReader();

		for (final AbstractEntity abstractEntity : this.abstractEntities.values()) {
			final CustomActionTemp customActionTemp = (CustomActionTemp) abstractEntity;

			final String id = customActionTemp.getId();

			final Command command = (Command) commandReader.getEntityWithId(customActionTemp.getCommandId());

			newEntities.put(id, new CustomAction(id, command));
		}
	}

	@Override
	public void read(final Document document) {
		this.read(CustomActionReader.ENTITY_NAME, document);
	}

	protected final void verifyRestrictions(final String id, final String commandId) {
		super.verifyRestrictions(id);

		if (commandId.isEmpty()) {
			throw new MissingAttributeException(ATTRIBUTE_COMMAND_ID);
		}
	}
}
